<template>
  <el-container>
    <el-header class="rigtop pdbt">
      <i class="fa el-icon-s-unfold" @click="clickFold" v-if="iconIf"></i> 
      <i class="fa el-icon-s-fold" @click="clickFold" v-if="!iconIf"></i>
      区域内计算公式信息
    </el-header>
      <el-main class="padding_top heiauto">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="90px"
          label-position="right">
          <el-form-item label="有效性" prop="fValid">
            <el-radio-group v-model="formData.fValid" size="mini">
              <el-radio v-for="(item, index) in fValidOptions" :key="index" :label="item.value"
                :disabled="item.disabled">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="计算类型" prop="fd">
            <el-radio-group v-model="formData.fd" size="mini" @change="agreeChange">
              <el-radio v-for="(item, index) in fdOptions" :key="index" :label="item.value"
                :disabled="item.disabled">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-row type="flex" justify="start" align="bottom" class="el_row_btn">
              <el-form-item label-width="5px" label="" prop="field1">
              <el-button type="primary" size="mini" @click="btnClick('+', '加')">&#43;</el-button>
              </el-form-item>
              <el-form-item label-width="5px" label="" prop="field2">
              <el-button type="primary" size="mini" @click="btnClick('-', '减')">&#45;</el-button>
              </el-form-item>
              <el-form-item label-width="5px" label="" prop="field3">
              <el-button type="primary" size="mini" @click="btnClick('*', '乘')">&#42;</el-button>
              </el-form-item>
              <el-form-item label-width="5px" label="" prop="field4">
              <el-button type="primary" size="mini" @click="btnClick('/', '除')">&#47;</el-button>
              </el-form-item>
              <el-form-item label-width="5px" label="" prop="field5">
              <el-button type="primary" size="mini" @click="btnClick('(', '(')">&#40;</el-button>
              </el-form-item>
              <el-form-item label-width="5px" label="" prop="field6">
              <el-button type="primary" size="mini" @click="btnClick(')', ')')">&#41;</el-button>
              </el-form-item>
              <el-form-item label-width="5px" label="" prop="field7">
              <el-button type="primary" size="mini" @click="btnClick('{', '{')">&#123;</el-button>
              </el-form-item>
              <el-form-item label-width="5px" label="" prop="field8">
              <el-button type="primary" size="mini" @click="btnClick('}', '}')">&#125;</el-button>
              </el-form-item>
          </el-row>
          <el-row type="flex" justify="start" align="bottom" class="el_row_btn">
              <el-form-item label-width="5px" label="" prop="field9">
              <el-button type="primary" size="mini" @click="btnClick('&&', '与')">&#38;&#38;</el-button>
              </el-form-item>
              <el-form-item label-width="5px" label="" prop="field10">
              <el-button type="primary" size="mini" @click="btnClick('||', '或')">&#124;&#124;</el-button>
              </el-form-item>
              <el-form-item label-width="5px" label="" prop="field11">
              <el-button type="primary" size="mini" @click="btnClick('>', '大于')">&#62;</el-button>
              </el-form-item>
              <el-form-item label-width="5px" label="" prop="field12">
              <el-button type="primary" size="mini" @click="btnClick('>=', '大于等于')">&#62;&#61;</el-button>
              </el-form-item>
              <el-form-item label-width="5px" label="" prop="field13">
              <el-button type="primary" size="mini" @click="btnClick('==', '等于')">&#61;&#61;</el-button>
              </el-form-item>
              <el-form-item label-width="5px" label="" prop="field14">
              <el-button type="primary" size="mini" @click="btnClick('<', '小于')">&#60;</el-button>
              </el-form-item> <el-form-item label-width="5px" label="" prop="field15">
                <el-button type="primary" size="mini" @click="btnClick('<=', '小于等于')">&#60;&#61;</el-button>
              </el-form-item>
              <el-form-item label-width="5px" label="" prop="field16">
              <el-button type="primary" size="mini" @click="btnClick('!=', '不等于')">&#33;&#61;</el-button>
              </el-form-item>
          </el-row>
          <!--
          <el-row type="flex" justify="start" align="bottom">
            <el-form-item label-width="1px" label="" prop="field159">
              <el-button type="primary" size="mini" @click="czfClick(' + ')">+</el-button>
            </el-form-item>
            <el-form-item label-width="1px" label="" prop="field158">
              <el-button type="primary" size="mini" @click="czfClick(' - ')">-</el-button>
            </el-form-item>
            <el-form-item label-width="1px" label="" prop="field156">
              <el-button type="primary" size="mini" @click="czfClick(' * ')">*</el-button>
            </el-form-item>
            <el-form-item label-width="1px" label="" prop="field164">
              <el-button type="primary" size="mini" @click="czfClick(' / ')">/</el-button>
            </el-form-item>
            <el-form-item label-width="1px" label="" prop="field165">
              <el-button type="primary" size="mini" @click="czfClick(' ( ')">(</el-button>
            </el-form-item>
            <el-form-item label-width="1px" label="" prop="field166">
              <el-button type="primary" size="mini" @click="czfClick(' ) ')">)</el-button>
            </el-form-item>
            <el-form-item label-width="1px" label="" prop="field167">
              <el-button type="primary" size="mini" @click="czfClick(' { ')">{</el-button>
            </el-form-item>
            <el-form-item label-width="1px" label="" prop="field168">
              <el-button type="primary" size="mini" @click="czfClick(' } ')">}</el-button>
            </el-form-item>
          </el-row>
          <el-row type="flex" justify="start" align="bottom">
            <el-form-item label-width="1px" label="" prop="field170">
              <el-button type="primary" size="mini" @click="czfClick(' && ')">&&</el-button>
            </el-form-item>
            <el-form-item label-width="1px" label="" prop="field171">
              <el-button type="primary" size="mini" @click="czfClick(' || ')">||</el-button>
            </el-form-item>
            <el-form-item label-width="1px" label="" prop="field172">
              <el-button type="primary" size="mini" @click="czfClick(' > ')">></el-button>
            </el-form-item>
            <el-form-item label-width="1px" label="" prop="field173">
              <el-button type="primary" size="mini" @click="czfClick(' >= ')">>=</el-button>
            </el-form-item>
            <el-form-item label-width="1px" label="" prop="field174">
              <el-button type="primary" size="mini" @click="czfClick(' == ')">==</el-button>
            </el-form-item>
            <el-form-item label-width="1px" label="" prop="field175">
              <el-button type="primary" size="mini" @click="czfClick(' < ')"><</el-button>
            </el-form-item>
            <el-form-item label-width="1px" label="" prop="field176">
              <el-button type="primary" size="mini" @click="czfClick(' <= ')"><=</el-button>
            </el-form-item>
            <el-form-item label-width="1px" label="" prop="field177">
              <el-button type="primary" size="mini" @click="czfClick(' != ')">)</el-button>
            </el-form-item>
          </el-row>
          -->
          <el-form-item label="添加单元格" prop="field196">
            <el-select v-model="tsCd" placeholder="选择索引表" clearable :style="{width: '100%'}" @change="loadExcel">
              <el-option v-for="(item, index) in field196Options" :key="index" :label="item.tsNm"
                :value="item.tsCd" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
          <el-table v-if="tableShow" border style="width:100%; margin-bottom:20px;line-height: 20px" :data="tableData" :row-style="{height: '20px'}" :cell-style="{margin:'10px'}">
            <el-table-column fixed="left" label="表" width="100">
              <template slot-scope="scope">
                <el-input v-model="scope.row.tsCd" type="text"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="有效范围" width="262">
              <template slot-scope="scope">
                <el-input v-model="scope.row.frang" type="text"></el-input>
              </template>
            </el-table-column>
          </el-table>
          <el-form-item label="计算单元格" prop="calCell">
            <el-input ref="calCell" v-model="formData.calCell" type="text" :style="{width: '100%'}" @focus="calCellFocus" placeholder="请输入计算单元格"></el-input>
          </el-form-item>
          <el-form-item label-width="1px" label="" prop="field178">
              <el-input ref="m_input" v-model="inputOne" type="textarea" @input="inputOneChange" @focus="formulaFocus" placeholder="请输入表内审核公式······"
              :autosize="{minRows: 10, maxRows: 1000}" :style="{width: '100%'}"></el-input>
          </el-form-item>
          <el-form-item label-width="1px" label="" prop="field179">
              <el-input ref="n_input" v-model="inputTwo" type="textarea" @focus="fDescFocus" placeholder="请输入审核解释······"
              :autosize="{minRows: 7, maxRows: 1000}" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-form>
      </el-main>
      <el-footer style="text-align: center;">
        <el-button type="primary" size="mini" :disabled="dissavebtn" @click="submitForm">确定</el-button>
        <el-button size="mini" :disabled="dissavebtn" @click="clearForm">重置</el-button>
      </el-footer>
      <vxe-modal  v-model="addFl" v-if="addFl" title="选中单元格" width="96%" height="96%" size="small" @close="addFlClose" destroy-on-close>
              <div ref="sheetmain" class="bk_full_wapper"></div>
      </vxe-modal>
  </el-container>
</template>
<script>
  import request from "@/utils/requestutil";
  import {getRealUrl, syncRequest} from "@/utils/httpRequet";
  import $ from "jquery";
  import treeExhide from "@/components/ztree/lib/jquery.ztree.exhide.min.js";
  import dicPanel from '@/hr/utils/dicPanel'
  import { options } from 'runjs';
  import psTree from '@/components/psTree/psTree';
  import { isNull } from 'xe-utils/methods';
  import functionSelector from '@/components/FunctionSelector/FunctionSelector'
  import xspreadsheet from "@/components/x-spreadsheet/xspreadsheet.js";
  import "@/components/x-spreadsheet/xspreadsheet.css";
export default {
  components: {
    psTree,
    dicPanel,
    functionSelector,
  },
  props: [],
  data() {
    return {
      iconIf: false,
      dissavebtn: true,
      // isFold: '0',
      isFoldz: '',
      tableShow:true,
      tableData:[],
      jsFlag: false,
      hasJszb: false,
      bzcode:"",
      ttId:"",
      tsCd:"",
      tsUn:"",//管理单位
      strType:"add",
      proofid:"",
      addFl:false,
      inputOne:"",
      inputTwo:"",
      formData: {
        fd:'COL',
        calCell: "",
        formula: "",
        prsord: "",
        tsCfgs: "",
        frang: "",
        fDesc: "",
        fValid: "1",
        bzcode: "",
        ttId: "",
        prUn: "",
        tsCd: "",
        proofid: "",
        command: "NEW",
      },
      rules: {
        fValid: [],
        field196: [],
        field178: [],
        field179: [],
        fd: [{
          required: true,
          message: '计算类型不能为空',
          trigger: 'change'
        }],
      },
      fValidOptions: [{
        "label": "有效",
        "value": '1'
      }, {
        "label": "无效",
        "value": '0'
      }],
      fdOptions: [{
        "label": "行计算",
        "value": 'ROW'
      }, {
        "label": "列计算",
        "value": 'COL'
      }, {
        "label": "其他",
        "value": 'OTHER'
      }],
      field196Options: [],
    }
  },
  computed: {},
  watch: {},
  created() {
  },
  mounted() {},
  methods: {
    clickFold() {
      if(this.isFold==='1'){
        this.isFold = '0'
        this.iconIf = false
      }else{
        this.isFold = '1'
        this.iconIf = true
      }
      this.isFoldz = this.isFold
      this.$emit('myclickFoldQY', this.isFoldz)
    },
    submitForm() {
      let strTableList = this.tableData;
      let frang = "";
      let tsCd = "";
      let tsCfgs = "";
      if(strTableList.length > 0){
        for(var i = 0;i<strTableList.length;i++){
          tsCfgs+= strTableList[i].tsCd+",";
          frang += "{\"tsCd\":\""+strTableList[i].tsCd+"\",\"frang\":\""+strTableList[i].frang+"\"},"
        }
        frang = frang.substring(0,frang.length-1);
        //console.log(frang);
        tsCfgs = tsCfgs.substring(0,tsCfgs.length-1);
        tsCd = strTableList[0].tsCd
      }else{
        this.$message.warning("公式范围不能为空！");
        return false;
      }
      let formula = this.$refs.m_input.$refs.textarea.value;
      let fDesc = this.$refs.n_input.$refs.textarea.value
      if (this.formData.fd != "OTHER") {
        if (tsCfgs != "") {
          let _tsCds = tsCfgs.split(",")
          for(var i = 0;i<_tsCds.length;i++){
            if (i > 0) {
              console.log(formula.indexOf(_tsCds[i]));
              if(formula.indexOf(_tsCds[i]) == -1){
                this.$message.warning("有效范围和公式不匹配，请修改后再保存！");
                return false;
              }
            }
          }
        }
      }
     
      this.formData.formula = formula
      this.formData.tsCfgs = tsCfgs
      this.formData.frang = frang
      this.formData.fDesc = fDesc
      this.formData.bzcode = this.bzcode
      this.formData.ttId = this.ttId
      this.formData.tsCd = tsCd
      if(this.strType == "add") {
        this.formData.prUn = this.$store.state.user.userInfo.deptId;//获取管理单位
        this.formData.command = "NEW"
      } else {
        this.formData.command = "UPDATE"
      }
      //console.log(this.formData);
      request({
        url:"editDcbjsQY2",
        method:"post",
        params:this.formData,
      }).then((data)=>{
        //console.log(data);
        this.$emit("refreshData",this.bzcode,this.ttId);
        //this.resetForm()
        if(data.data.success){
          this.$message.success((this.strType == "add" ? "新增" : "修改") + "成功！");
          this.clearAll()
        }else{
          this.$message.error((this.strType == "add" ? "新增" : "修改") + "失败！");
        }
      })
    },
    resetForm(obj) {
      console.log("resetForm",obj);
      this.strType="add";
      this.bzcode= obj.val.bzcode;
      this.ttId = obj.val.ttId;
      this.proofid = "";
      this.formData.fValid = "1";
      this.inputOne = "";
      this.inputTwo = "";
      this.$refs['elForm'].resetFields();
      this.$refs.m_input.$refs.textarea.value = "";
      this.$refs.n_input.$refs.textarea.value = "";
      this.tableShow=true;
      this.tableData = [];
      this.formData = {fd:'COL',calCell: "",formula: "",prsord: "",tsCfgs: "",frang: "",fDesc: "",fValid: "1",bzcode: "",ttId: "",prUn: "",tsCd: "",proofid: "",command: "NEW",}
      this.dygSelectData()
      this.dissavebtn = false
    },
    clearForm(){
      this.$refs['elForm'].resetFields()
      this.$refs.m_input.$refs.textarea.value = "";
      this.$refs.n_input.$refs.textarea.value = "";
      this.tableData = [];
      this.formData = {fd:'COL',calCell: "",formula: "",prsord: "",tsCfgs: "",frang: "",fDesc: "",fValid: "1",bzcode: "",ttId: "",prUn: "",tsCd: "",proofid: "",command: "NEW",}
    },
    clearAll() {
      this.clearForm()
      this.dissavebtn = true
    },
    //加载（添加单元格）下拉框
    dygSelectData(){
      request({
        url:"bjshListSelect",
        method:"post",
        params:{bzcode:this.bzcode,ttid:this.ttId},
      }).then((data)=>{
        //console.log(eval(data.data));
        this.field196Options = data.data;
      })
    },
    loadExcel(){
      console.log("loadExcel:");
      let $t = this;
      $t.tscd = $t.formData.field196;
      $t.tsUn = $t.$store.state.user.userInfo.deptId;//获取管理单位
      this.addFl = true;
      this.$nextTick(function () {
        //初始化表单
        const option = {
          mode:'read',
          showToolbar: false,
          showZeroNumber: false,
          showGrid:false,
          height: $t.$refs.sheetmain.clientHeight,
          width: $t.$refs.sheetmain.clientWidth,
        };
        $t.workbook =new x_spreadsheet($t.$refs.sheetmain, option);
        $t.workbook.loadData([{
          rows: { len: 20 },
          clos: { len: 10 },
          name: "sheet1",
        }]);
        //绑定Excel的双击事件
        $t.workbook.on("cell-dblclick",function(){
          console.log(arguments)
          //根据X、Y坐标查询该位置的区域
          if(arguments < 3){
            $t.$message.warning("未获取到对应单元格坐标，请刷新或联系管理员");
            return false;
          }
          let x = arguments[1];
          let y = arguments[2]
          request({
            url:"bjshQYGetAreaCd",
            method:"post",
            params:{bzcode:$t.bzcode,ttId:$t.ttId,tsCd:$t.tsCd,tsUn:$t.tsUn,x:x,y:y},
          }).then((data)=>{
            let areaNm = "0";
            if(data.data.length > 0){
              areaNm = data.data.areaNm;
            }else{
              areaNm="0";
            }
            //根据选择的单元格动态添加table行
            let myField = $t.$refs.m_input.$refs.textarea.value;
            if(myField.indexOf($t.tsCd) == -1){
              //判断是否选中“计算指标”
              if ($t.jsFlag) {
                if ($t.hasJszb) {
                  $t.tableData.shift()
                }
                $t.tableData.unshift({
                  "tsCd":$t.tsCd,
                  "frang":"",					
                });
                $t.hasJszb = true
              } else {
                $t.tableData.push({
                  "tsCd":$t.tsCd,
                  "frang":"",					
                });
              }
            }
            let strAll = "@"+$t.tsCd+"@"+areaNm+"@"+x+"@"+y+" ";
            $t.btnClick(strAll);
          })
        })
      });

     
      request({//查询模板json
        url:"bjshQYExcelJson",
        method:"post",
        params:{bzcode:$t.bzcode,ttId:$t.ttId,tsCd:$t.tsCd,tsUn:$t.tsUn}
      }).then((data)=>{
        if(data.data.length>0){
          $t.workbook.loadData(eval(data.data[0].tsTemp));
        }else{
          $t.$message.warning("该表没有配置模板,请刷新或者联系管理员！");
          return false;
        }
      })
    },
    btnClick(strNum, strDesc){//用于追加或插入计算符号或要审核字段名称
      if (!this.jsFlag) {
        const myField = this.$refs.m_input.$refs.textarea;
        if (myField.selectionStart || myField.selectionStart === 0) {
          let startPos = myField.selectionStart;
          let endPos = myField.selectionEnd;
          myField.value = myField.value.substring(0, startPos) + strNum + myField.value.substring(endPos, myField.value.length);
          myField.focus();
          myField.selectionStart = startPos + strNum.length;
          myField.selectionEnd = startPos + strNum.length;
        } else {
          this.formData.formula += strNum
        }
      } else {
        if (this.formData && this.formData.command=="NEW") {
          this.formData.calCell = strNum.replace(" ", "")
        }
      }
    },
    //计算类型点击事件
    agreeChange(){
      if(this.formData.fd=="OTHER"){
        this.tableShow=false
        this.$refs.m_input.$refs.textarea.value = "";
      }else{
        this.tableShow=true;
        this.tableData=[];
      }
    },
    //回显数据
    setData(val){
      this.formData = {}
      this.formData.fd=val.val.fd;
      //console.log("bjmright-setData:",val);
      //this.formData.fd = val.val.fd;
      this.strType=val.type;//是修改update还是新增add
      this.bzcode= val.val.bzcode;
      this.ttId = val.val.ttId;
      this.proofid = val.val.proofid;
      this.formData.fValid = val.val.fValid;
      this.inputOne = val.val.formula;
      this.inputTwo = val.val.fDesc;
      this.$refs.m_input.$refs.textarea.value = val.val.formula;
      this.$refs.n_input.$refs.textarea.value = val.val.fDesc;
      let frang = JSON.parse(val.val.frang)
      this.tableData=[];
      if(frang.length > 0){
        for(var i = 0;i<frang.length;i++){
          this.tableData.push({
            "tsCd":frang[i].tsCd,
            "frang":frang[i].frang,					
          });
        }
      }
      this.tableShow=(this.formData.fd == "OTHER") ? false : true;
      this.formData.calCell=val.val.calCell;
      this.formData.formula=val.val.formula;
      this.formData.prsord=val.val.prsord;
      this.formData.tsCfgs=val.val.tsCfgs;
      this.formData.frang=val.val.frang;
      this.formData.fDesc=val.val.fDesc;
      this.formData.fValid=val.val.fValid;
      this.formData.bzcode=val.val.bzcode;
      this.formData.ttId=val.val.ttId;
      this.formData.prUn=val.val.prUn;
      this.formData.tsCd=val.val.tsCd;
      this.formData.proofid=val.val.proofid;
      this.formData.command="UPDATE";
      this.dygSelectData()
      this.dissavebtn = false
    },
    calCellFocus(val) {
      //console.log("calCellFocus",val);
      this.jsFlag = true
    },
    formulaFocus(val) {
      this.jsFlag = false
    },
    fDescFocus(val) {
      this.jsFlag = false
    },
    inputOneChange(){
      let tableDataList = this.tableData;
      let inputVal = this.$refs.m_input.$refs.textarea.value;
      inputVal = inputVal.replace(/^\s*|\s*$/g,"");
      if(inputVal.indexOf('@') != -1){
        for(var i=1;i<tableDataList.length;i++){
          if(inputVal.indexOf(tableDataList[i].tsCd) == -1){
            this.tableData.splice(i,1);
          }
        }
      }
    },
    addFlClose(obj) {
      console.log(obj);
      this.tsCd = undefined
    }
  }
}

</script>
<style lang="scss" scoped>
.padding_top .el-form{
  padding: 0 10px; 
}


.el_row_btn .el-button--mini{
  padding:4px 6px;
  width:100%;
}
.padding_top .el_row_btn .el-form-item{
  margin-bottom: 0px;
  flex: 1;
  margin-top:0;
}
.padding_top .el-form-item{
  margin-top: 6px;
  margin-bottom: 6px;
}
.padding_top .el-textarea{
  margin-top: 8px;
  margin-bottom: 8px;
}
::v-deep .el-form-item--medium .el-form-item__label{
  text-align: right;
}
::v-deep .padding_top .el-form-item--medium .el-form-item__content{
  line-height: 30px;
}
</style>
